<template>
    <main-wrap>
        <template v-slot:header>
            <Header :title="detailType==2?'拍卖出价':'商品购买'"/>
        </template>
        <div class="content">
            <Addres/>
            <div>
                <ul class="shoppingList">
                    <li>
                        <a>
                            <div class="imgBox">
                                <Image :url="detail.imageUrl" />
                            </div>
                            <div class="con">
                                <h3>{{detail.title}}</h3>
                                <div class="price">
                                    <!-- <s v-if="parseFloat(oldPrice)>parseFloat(price)">￥{{oldPrice}}</s> -->
                                    <span>￥<b>{{price}}</b></span>
                                    <!-- <em>x1</em> -->
                                </div>
                            </div>
                        </a>
                    </li>
                </ul>

                <div class="payTypeItem p40">
                    <label>数量</label>
                    <span class="rbox">
                        <van-stepper v-model="num" :disabled="detailType==2"/>
                    </span>
                </div>

                <div class="payTypeItem">
                    <label>配送</label>
                    <div class="rbox">
                        <p class="txt">快递运输</p>
                        <p class="txt">工作日、双休日与节假日均可送货</p>
                    </div>
                </div>

                <div class="payTypeItem">
                    <label>商品金额</label>
                    <span v-if="price" class="rbox"><b>￥{{price*num}}</b></span>
                </div>

                <div class="payTypeItem">
                    <label>运费</label>
                    <span v-if="freightData.decimalTwoString" class="rbox"><b>￥{{freightData.decimalTwoString}}</b></span>
                    <span v-else class="rbox">全场包邮</span>
                </div>

                <div class="dkou">
                    <h5>抵扣</h5>
                    <div class="payTypeItem" v-if="redPacketData.totalAmount">
                        <div class="label">
                            <my-checkbox v-model="redpg" :disabled="redPacketData.availableAmount.num<=0">红包</my-checkbox>
                        </div>
                        <div class="rbox">
                            <b>￥{{redPacketData.availableAmount.decimalTwoString}}</b>
                            <p>可抵扣{{redPacketData.availableAmount.num>price?price:redPacketData.availableAmount.decimalTwoString}}元</p>
                        </div>
                    </div>
                    <div class="payTypeItem" v-if="integralData.totalAmount">
                        <div class="label">
                            <my-checkbox v-model="point" :disabled="integralData.availableAmount.num<=0">积分</my-checkbox>
                        </div>
                        <div class="rbox">
                            <b>{{integralData.totalAmount.num}}</b>
                            <p>可抵扣{{Math.floor(integralData.availableAmount.num/1000)}}元</p>
                        </div>
                    </div>
                </div>

                
            </div>
        </div>

        <template v-slot:footer>
            <div class="bottomBox">
                <div class="price">¥<b>{{totalPrice}}</b></div>
                <!-- <div class="buyBtn" v-if="detailType==2" @click="auctionOffer">确定</div> -->
                <div class="buyBtn" :class="{'disabled':!useAdress.addresseeId}" @click="gopay">立即付款</div>
            </div>
        </template>
        <pay-type v-model:show="showPayType" @change="selectPayType"/>
    </main-wrap>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,onMounted,computed,watch } from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import {
    Checkbox as vanCheckbox,
    Stepper as vanStepper,
    Popup as vanPopup
} from 'vant'
import Header from '@/components/header.vue'
import mainWrap from '@/components/mainWrap.vue'
import Addres from './components/addres.vue'
import Image from "@/components/image.vue"
import myCheckbox from '@/components/myCheckbox.vue'
import payType from '@/components/payType.vue'
import { toast,H5CallAPPFuction } from '@/utils/common'

export default {
    components:{
       mainWrap,
       Header,
       Addres,
       Image,
       vanCheckbox,
       vanStepper,
       vanPopup,
       myCheckbox,
       payType
    },
    props:{

    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()

        const state = reactive({
            useAdress:computed(()=>store.state.arApi.useAdress),
            detail:computed(()=>store.state.arApi.detail),
            detailType:computed(()=>store.state.arApi.detailType),  // 1为直卖商品详情，2为拍卖详情
            redpg:false,
            point:false,
            num:1,
            price:0,
            redPacketData:'',
            integralData:'',
            totalPrice:0,
            freightData:{}, // 运费信息
            showPayType:false,
            payOrderNo:''
        })
        
        onMounted(()=>{
            if(!state.detail.goodsId) return router.back()
            
            // 定义payResult方法，供app调用(app支付完成调用)
            window['payResult'] = function (status,msg) {
                // data为App传递过来的值
                //alert('app调用H5成功，参数为：'+status)
                if(status==1){
                    router.push('/pay/success')
                }else{
                    router.push(`/pay/fail?msg=${JSON.stringify(msg) || ''}`)
                } 
            }

            state.price = route.query.price || state.detail.internalPrice.num  // 商品单价
            // 保存路径 ,用于新增地址时，可以直接返回到这个页面
            store.commit('arApi/set_backUrl',route.fullPath)
            get_redPacket()
            get_integral()
            if(state.useAdress.addresseeId){
                get_freight()  // 获取运费
            }else{
                get_latest_address()
            }
        })

        // watch(()=>state.useAdress,(n,o) =>{
        //     console.log("TTTTT",n)
        //     get_freight()  // 获取运费
        // })

        state.totalPrice = computed(()=>{
            let total = state.price * state.num + (state.freightData.num || 0) // 单价*数量+运费
            if(state.redpg){  // 红包抵扣
                total = total - state.redPacketData.availableAmount.num*1 
            }
            if(state.point){  // 积分抵扣
                total = total - Math.floor(state.integralData.availableAmount.num/1000) // 按1000:1计算可抵扣金额；
            }
            return total>0?total.toFixed(2):0
        })

        // 获取红包
        const get_redPacket = ()=>{
            store.dispatch("arApi/get_cash_balance").then(res=>{
                res.success && (state.redPacketData = res.data)
            })
        }
        // 获取积分
        const get_integral = () =>{
            store.dispatch("arApi/get_integral").then(res=>{
                res.success && (state.integralData = res.data)
            })
        }
        // 获取最近的收货地址
        const get_latest_address = ()=>{
            store.dispatch("arApi/get_latest_address").then(res=>{
                if(res.success){
                    if(res.data){
                        store.commit('arApi/set_useAdress',res.data)
                        get_freight() // 获取运费
                    }
                    
                }
            })
        }
        // 获取运费
        const get_freight=()=>{
            store.dispatch("arApi/get_freight",{
                goodsId: state.detail.goodsId,
                province: state.useAdress.provinceName
            }).then(res=>{
                if(res.success){
                    state.freightData = res.data
                }
            }) 
        }
        const gopay = ()=>{
            if(!state.useAdress.addresseeId) return

            if(state.detailType==2){  // 竞拍出价
                auctionOffer()
            }else{  // 直购
                direct_buy_creade_order()
            }
        }

        // 选择支付方式后回调处理
        const selectPayType =(payType)=>{
            creade_pay_order(payType)  // 创建支付订单
        }

        // 直购创建订单
        const direct_buy_creade_order = (payType)=>{
            store.dispatch("arApi/direct_buy_creade_order",{
                goodsId: state.detail.goodsId,
                cashCouponEnable: state.redpg,  // 是否使用代金券
                //goodsAttr: "", // 商品规格 多个用|分隔 红色|大号
                goodsId: state.detail.goodsId,
                payType: payType, // 支付类型（微信支付 WECHAT_PAY，支付宝 ALIPAY）
                quantity: state.num,  // 购买数量
                subPayType: "APP", //支付唤起方式 H5 ， APP， APPLET:小程序 默认H5
                tpDeductionEnable: state.point, // 是否使用积分抵扣
                userShippingAddressId: state.useAdress.addresseeId// 收货地址id
            }).then(res=>{
                if(res.success){
                    if(res.data.needPay){ // 需要调起支付，则选择支付方式
                        state.payOrderNo = res.data.payOrderNo
                        state.showPayType=true
                    }else{
                        router.push('/pay/success')
                    }
                    
                    // 创建支付订单。获取支付参数
                    //creade_pay_order(res.data.payOrderNo,payType)
                }else{
                    toast(res.message)
                }
            })
        }
        // 创建支付订单，获取支付参数
        const creade_pay_order = async (payType)=>{
            const res = await store.dispatch('arApi/creade_pay_order',{
                payOrderNo:state.payOrderNo,  // 支付订单号
                payType: payType, // 支付类型（微信支付 WECHAT_PAY，支付宝 ALIPAY）	
                //requestIp: "192.168.3.112", // 	用户IP
                returnUrl: "https://www.tst.metayuanjie.com/api/union/callback/pay/appPay", // 页面回执地址
                subPayType: "APP", // 	支付唤起方式 H5 APP APPLET 小程序 默认APP
                //userId: "" // 用户标识: 对应微信的openid或者支付宝的userId
            })
            if(res.success){
                // 把参数给app，用于呼起支付
                const appParams = {payType,...res.data}
                try {
                    H5CallAPPFuction('payOrder',JSON.stringify(appParams))  // 调用app的payOrder方法，传入支付参数
                } catch (error) {
                    toast('调用app失败')
                }
                state.showPayType = false
                
            }else{
                 toast(res.message)
            }
        }

        // 拍卖出价(创建拍卖出价订单)
        const auctionOffer = async (payType)=>{
            const res = await store.dispatch('arApi/offer',{
                bidAmount:state.price.toString(),
                goodsId:state.detail.goodsId,
                payType, //支付类型（微信支付 WECHAT_PAY，支付宝 ALIPAY）
                subPayType:'H5', //支付唤起方式 H5 ， APP， APPLET:小程序 默认H5
                userShippingAddressId:state.useAdress.addresseeId //收货地址
            })
            if(res.success){
                if(res.data.needPay){ // 需要调起支付，则选择支付方式
                    state.payOrderNo = res.data.payOrderNo
                    state.showPayType=true
                }else{
                    router.push('/pay/success')
                }
                // 创建支付订单。获取支付参数
                //creade_pay_order(res.data.payOrderNo,payType)
            }else{
                toast(res.message)
            } 
        }

        return{
            ...toRefs(state),
            auctionOffer,
            direct_buy_creade_order,
            selectPayType,
            gopay
        }
    }
}
</script>

<style lang="scss" scoped>
    .content{
        padding: 30px 40px;
    }
    .shoppingList{
        margin: 0;
        padding: 30px 0;
        li{
            padding: 0;
            h5{
                display: flex;
                height: 50px;
                align-items: center; 
                padding: 0 40px;
                margin: 0;
                align-items: center;
                font-weight: normal;
                font-size: 28px;
                img{
                    display: block;
                    height: 30px;
                    margin: 0 15px 0 0;
                }
            }
            a{
                padding: 0;
                display: flex;
                color: #fff;
                .imgBox{
                    width: 150px;
                    height: 150px;
                    overflow: hidden;
                }
                .con{
                    flex: 1;
                    padding: 0 0 0 30px;
                    overflow: hidden;
                    h3{
                        height: 85px;
                        line-height: 46px;
                        font-size: 28px;
                        font-weight: normal;
                        text-overflow: -o-ellipsis-lastline;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        line-clamp: 2;
                        -webkit-box-orient: vertical;
                    }
                    .price{
                        display: flex;
                        height: 40px;
                        line-height: 40px;
                        color: var(--baseColor);
                        margin: 30px 0 0 0;
                        font-size: 26px;
                        span{
                            flex: 1;
                            b{
                                font-size: 42px;
                                font-weight: normal;
                                padding: 0 0 0 5px;
                            }
                        }
                        em{
                            font-style: normal;
                        }
                        s{
                            margin: 0 10px 0 0;
                            color: #c2c2c2;
                        }
                    }
                }
            }
        }
    }
    .payTypeItem{
        display: flex;
        min-height: 100px;
        align-items: center; 
        margin: 0;
        padding: 30px 0;
        color: var(--baseColor);
        border-top: 1px solid rgba(217, 217, 217, 0.3);
        &.p40{
          padding-top: 40px;  
          padding-bottom: 40px; 
        }
        label,.label{
            flex: 1;
            font-size: 30px;
            font-weight: 500;
        }
        .rbox{
            padding: 0 10px 0 0;
            text-align: right;
            color: #fff;
            b{
                font-size: 36px;
                font-weight: normal;
                color: var(--baseColor);
            }
            .txt{
                font-size: 26px;
                line-height: 40px;
            }
        }
        i{
            font-size: 24px;
            color: #c2c2c2;
        }
    }
    .dkou{
        border-top: 1px solid rgba(217, 217, 217, 0.3);
        margin: 0;
        h5{
            font-size: 30px;
            font-weight: 500;
            color: var(--baseColor);
            padding: 60px 0 0 0;
        }
        .payTypeItem{
            border: 0;
            margin-top:0 ; 
            background: #0E6161;
            margin-top:20px ;
            padding: 20px 30px;
            .rbox{
                p{
                    font-size:28px ;
                }
            }
        }
    }
    .bottomBox{
        display: flex;
        height: 100px;
        width: 100%;
        background: rgba(14, 97, 97, 0.8);
        .price{
            flex: 1;
            padding: 0 30px;
            line-height: 100px;
            font-weight: 500;
            font-size: 40px; 
            b{
                padding: 0 0 0 7px;
                font-weight: 500;
            }
        }
        .buyBtn{
            width: 250px;
            background: var(--baseColor);
            font-size: 36px;
            line-height: 100px;
            text-align: center;
            color: #fff;
            font-weight: 500;
            &:active{
                background: #eea454;
            }
            &.disabled{
                background: #A7A7A7;
                color: #DDDDDD;
            }
        }
    }
    
</style>

<style lang="scss">
    .payTypeItem{
        .van-stepper__minus,.van-stepper__plus{
            width: 40px;
            height: 40px;
            background: url('/images/jian.png') left top no-repeat;
            background-size: 40px 40px;
            border-radius: 0;
            opacity: 1;
            margin: 0 10px 0 0;
            &::after,&::before{
                display: none;
            }
            &.van-stepper__minus--disabled{
                opacity: 0.5;
            }
        }
        .van-stepper__plus{
            background-image: url('/images/jia.png');
            margin: 0 0 0 10px;
        }
        .van-stepper__input{
            width: 100px;
            height: 60px;
            background: url('/images/nbbg.png') left top no-repeat;
            background-size: 100% 100%;
            font-size: 30px;
            color: #fff;
        }
    }
</style>